'use strict';

const Controller = require('egg').Controller;

class NotifyController extends Controller {
  // 接收微信支付结果通知
  async wechatPay() {
    console.log('weappPaymentNotify');
    const params = await this.app.wechatPay.parse(this.ctx.request.body);
    console.log('params', params);
    const { out_trade_no, total_fee } = params;
    console.log('out_trade_no, total_fee', out_trade_no, total_fee);
    const trade = await this.ctx.model.Trade.findByPk(out_trade_no, {
      include: [
        {
          model: this.ctx.model.Order,
          include: [
            {
              model: this.ctx.model.User,
            },
            {
              model: this.ctx.model.Coupon,
            },
            {
              model: this.ctx.model.Store,
            },
          ],
        },
      ],
    });
    console.log('app Controller wechatPay trade', trade);
    const { price, status, orderId } = trade;
    console.log('price, status', price, status);
    if (Number(total_fee) === price) {
      const orderItem = await this.ctx.model.OrderItem.findOne({ where: { orderId } });
      console.log('Number(total_fee) === price itemId', orderItem.itemId);
      const { itemType, storeId } = await this.ctx.model.Item.findByPk(orderItem.itemId);
      console.log('Number(total_fee) === price itemType', orderItem.itemId);
      switch (itemType) {
        case 'present':
          if (status === 'unpaid') {
            await trade.update({ status: 'paid' });
            const order = await trade.getOrder();
            await order.update({ status: 'completed', userStatus: 'completed' });
            const purchaseUser = await this.ctx.model.User.findByPk(order.userId);
            console.log('purchaseUser.inviterId status ===', purchaseUser);
            await purchaseUser.update({ role: 'member' });
            await orderItem.update({ status: 'completed', userStatus: 'completed' });
            if (purchaseUser.inviterId) {
              const inviter = await this.ctx.model.User.findByPk(purchaseUser.inviterId);
              await this.ctx.service.member.index(inviter, purchaseUser);
            }
          }
          break;
        case 'commodities':
          if (status === 'unpaid') {
            const store = await this.ctx.model.Store.findByPk(storeId);
            const storeClass = await this.ctx.model.StoreClass.findByPk(store.storeClassId);
            const newOveRall = Number(store.oveRall) + price;
            const newStoreClassOveRall = Number(storeClass.oveRall) + price;
            await storeClass.update({ oveRall: newStoreClassOveRall });
            await store.update({ oveRall: newOveRall });
            await trade.update({ status: 'paid' });
            const order = await trade.getOrder();
            if (store.storeType === 'reserve') {
              await order.update({ status: 'completed' });
            } else {
              await order.update({ status: 'completed', userStatus: 'completed' });
            }
            // 商家订单通知
            const sendData = {
              phone: store.phone,
              TemplateCode: 'SMS_158547442',
            };
            await this.ctx.service.smsCode.send(sendData);
            const coupon = await order.getCoupon();
            if (coupon) await coupon.update({ usedAt: order.createdAt });
          }
          break;
        default:
      }

      this.app.wechatPay.success(this.ctx);
    }
  }
}

module.exports = NotifyController;
